// stores/auth.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {useRouter} from 'vue-router'
import {logoutApi} from '@/api/auth.api.ts'
// 类型定义
interface AuthTokens {
  accessToken: string
  refreshToken: string
}

interface User {
  id: string
  account: string
  avatar?: string
}

type btnList = {
  id: string
  name: string
  type: string
  code: string
}[]

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const tokens = ref<AuthTokens | null>(null)
  const btnList = ref<btnList[]>([])
  const router = useRouter();

  // 设置用户信息
  const setUser = (userData: User) => {
    user.value = { ...userData }
  }

  // 更新用户信息（部分更新）
  const updateUser = (partialUser: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...partialUser }
    }
  }

  // 设置令牌
  const setTokens = (newTokens: AuthTokens) => {
    tokens.value = { ...newTokens }
  }

  // 登录方法
  const login = (userData: User, authTokens: AuthTokens) => {
    setUser(userData)
    setTokens(authTokens)
  }

  // 登出方法
  const logout = async () => {
    await logoutApi({userId: user?.value?.id});
    user.value = null
    tokens.value = null
    btnList.value = [];
    await router.replace('/login');
  }

  // 检查是否登录
  const isAuthenticated = () => {
    return !!user.value && !!tokens.value?.accessToken
  }

  // 获取访问令牌
  const getAccessToken = () => {
    return tokens.value?.accessToken || null
  }

  const setBtnList = (list: btnList[]) => {
    btnList.value = list;
  }

  return {
    user,
    tokens,
    btnList,
    setBtnList,
    setUser,
    updateUser,
    setTokens,
    login,
    logout,
    isAuthenticated,
    getAccessToken
  }
}, {
  persist: {
    key: 'auth-store',
    storage: localStorage,
    // paths: ['user', 'tokens'],
    serializer: {
      serialize: JSON.stringify,
      deserialize: JSON.parse
    }
  }
})
